<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 管理员角色与权限处理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: role.php 1 2014-01-13 15:05:51Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Manager_Role
{

    /**
     * 缓存 ID
     *
     * @var string
     */
    public static $cache_id = '__manager_role';

    /**
     * 权限控制数据
     *
     * @var array
     */
    protected $_rules = NULL;

    /**
     * 载入会员角色数据
     *
     * @param  int  $member_id
     * @return array
     */
    public function get($member_id)
    {
        static $roles = NULL;

        if ( ! isset($roles[$member_id]))
        {
            $roles[$member_id] = DB::select('role.role_id', 'role.role_name')
                ->from(array('managers', 'man'))
                ->join(array('manager_roles', 'role'), 'INNER')
                ->on('man.role_id', '=', 'role.role_id')
                ->where('man.member_id', '=', $member_id)
                ->fetch_row();
        }

        return $roles[$member_id];
    }

    /**
     * 载入权限控制数据
     *
     * @return array
     */
    public function get_rules()
    {
        if ($this->_rules === NULL)
        {
            $this->_rules = Cache::instance()->get(self::$cache_id);

            if ($this->_rules === NULL)
            {
                $rows = DB::select(
                        'role.role_id', 'priv.token'
                    )
                    ->from(array('manager_roles', 'role'))
                    ->join(array('manager_rules', 'rule'), 'INNER')
                    ->on('rule.role_id', '=', 'role.role_id')
                    ->join(array('manager_privileges', 'priv'), 'INNER')
                    ->on('priv.priv_id', '=', 'rule.priv_id')
                    ->fetch_all();
                $this->_rules = array();
                foreach ($rows as $row)
                {
                    $this->_rules[$row['role_id']][] = $row['token'];
                }

                Cache::instance()->set(self::$cache_id, $this->_rules, 2592000); // 缓存一个月
            }
        }

        return $this->_rules;
    }

    /**
     * 判断是否拥有访问权限
     *
     * @param  int     $role_id
     * @param  string  $privilege
     * @return bool
     */
    public function is_allow($role_id, $privilege)
    {
        $rules = $this->get_rules();
        if (isset($rules[$role_id]) AND in_array($privilege, $rules[$role_id]))
        {
            return TRUE;
        }

        return FALSE;
    }

    /**
     * 重新加载权限
     */
    public function flush()
    {
        $this->_rules = NULL;

        Cache::instance()->delete(self::$cache_id);

        return $this;
    }

}